import {post} from '../../../utils/axios'

const state = {
  name: '新增资源',
  dialog: false,
  fields: {},
  valid: null,
  ipRules: [
    (v) => !!v || '请输入ip地址'
  ],
  msg: {
    ipAddress: '',
    subnet: '',
    gateway: ''
  }
}

const mutations = {
  closeNewIps: (state, payload) => {
    state.dialog = false
  },
  saveIps (state, payload) {
    if (payload.validate()) {
      post('/ips/',
        state.fields
      ).then((response) => {
        state.dialog = false
      }).catch((error) => {
        if (error.response.data) {
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
            console.log(state.msg)
          }
        }
      })
    }
  },
  newIpsDialog (state, payload) {
    payload.reset()
    let msg = state.msg
    for (var i in msg) {
      msg[i] = ''
    }
  }
}

const actions = {
  closeNewIps ({commit}) {
    commit('closeNewIps')
  },
  saveIps ({commit}, payload) {
    commit('saveIps', payload)
  },
  newIpsDialog ({commit, state}, payload) {
    commit('newIpsDialog', payload)
    if (!state.dialog) {
      this.dispatch('listips/handlerIps')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
